// 游戏常量
let GAME_WIDTH = window.innerWidth;
let GAME_HEIGHT = window.innerHeight;
const PLAYER_SPEED = 1.5; //玩家移动速度
const BULLET_SPEED = 12; // 提高子弹速度
let BASE_ENEMY_SPEED = 0.5; // 降低基础速度
let RESOURCE_SPAWN_RATE = 0.001; // 降低经验值复活频率
let ENEMY_SPAWN_RATE = 1; // 提高敌人生成率
const AUTO_AIM_RANGE = 2000; // 自动瞄准范围
const ENEMY_ATTACK_RANGE = 200; // 敌人攻击范围
const ENEMY_ATTACK_COOLDOWN = 2000; // 敌人攻击冷却时间（毫秒）
const ENEMY_PROJECTILE_SPEED = 5; // 敌人子弹速度
const PLAYER_BULLET_SIZE = 4; // 玩家子弹大小
const ENEMY_BULLET_SIZE = 3; // 敌人子弹大小
const BULLET_TRAIL_LENGTH = 20; // 子弹拖尾长度

// 升级系统常量
const UPGRADE_COSTS = {
    speed: 100,
    damage: 150,
    shield: 200
};

// 添加屏幕适配相关常量
const SCREEN_MODES = {
    WINDOWED: 'windowed',
    FULLSCREEN: 'fullscreen'
};

// 游戏状态
let gameState = null;
let gameContext = null;

// 键盘状态
let keys = {
    w: false,
    s: false,
    a: false,
    d: false,
    space: false
};

// 游戏设置
let gameSettings = {
    volume: 50,
    difficulty: 'medium',
    enemySpeed: 3,
    screenMode: SCREEN_MODES.WINDOWED,
    // 添加难度相关的设置
    difficultySettings: {
        easy: {
            enemySpawnRate: 0.0005,
            baseEnemySpeed: 0.3,
            resourceSpawnRate: 0.008
        },
        medium: {
            enemySpawnRate: 0.001,
            baseEnemySpeed: 0.5,
            resourceSpawnRate: 0.005
        },
        hard: {
            enemySpawnRate: 0.002,
            baseEnemySpeed: 0.7,
            resourceSpawnRate: 0.003
        }
    }
};

// 添加护盾效果配置
const SHIELD_EFFECT_CONFIG = {
    orbitCount: 6,          // 光环数量
    baseRadius: 60,         // 基础半径
    orbitSpeed: 0.02,       // 旋转速度
    pulseRange: 10,         // 脉冲范围
    pulseSpeed: 0.05,       // 脉冲速度
    color: '#00a2ff',       // 基础颜色
    glowColor: '#80d4ff'    // 发光颜色
};

// 添加子弹追踪配置
const BULLET_CONFIG = {
    speed: BULLET_SPEED,
    turnSpeed: 0.15,         // 子弹转向速度
    maxTrackingRange: 800,   // 最大追踪范围
    trackingStrength: 0.8    // 追踪强度
};

// 游戏主循环
function gameLoop() {
    if (!gameContext || !gameState) return;
    
    // 清空画布
    gameContext.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
    
    // 如果游戏结束或暂停，只重新渲染画面
    if (gameState.gameOver || gameState.paused) {
        render(gameContext);
        gameState.animationFrameId = requestAnimationFrame(gameLoop);
        return;
    }
    
    // 更新游戏状态
    update();
    
    // 渲染画面
    render(gameContext);
    
    // 继续游戏循环
    gameState.animationFrameId = requestAnimationFrame(gameLoop);
}

// 更新游戏状态
function update() {
    if (!gameState || gameState.gameOver || gameState.paused) return;
    
    // 确保所有数组都已初始化
    if (!gameState.bullets) gameState.bullets = [];
    if (!gameState.enemies) gameState.enemies = [];
    if (!gameState.missiles) gameState.missiles = [];
    if (!gameState.lasers) gameState.lasers = [];
    if (!gameState.particles) gameState.particles = [];
    if (!gameState.resources) gameState.resources = [];
    if (!gameState.scoreTexts) gameState.scoreTexts = [];
    
    // 更新玩家
    updatePlayer();
    
    // 更新子弹
    if (gameState.bullets.length > 0) {
        updateBullets();
    }
    
    // 更新敌人
    if (gameState.enemies.length > 0) {
        updateEnemies();
    }
    
    // 更新导弹
    if (gameState.missiles.length > 0) {
        updateMissiles();
    }
    
    // 更新激光
    if (gameState.lasers.length > 0) {
        updateLasers();
    }
    
    // 更新粒子效果
    if (gameState.particles.length > 0) {
        updateParticles();
    }
    
    // 更新资源
    if (gameState.resources.length > 0) {
        updateResources();
    }
    
    // 检查碰撞
    checkCollisions();
    
    // 生成新资源
    if (Math.random() < RESOURCE_SPAWN_RATE) {
        spawnResource();
    }
    
    // 生成新敌人
    if (Math.random() < ENEMY_SPAWN_RATE && gameState.enemies.length < 5) {
        spawnEnemy();
    }
    
    // 更新技能图标
    updateAbilityIcons();
    
    // 更新技能冷却
    updateAbilities();
    
    // 更新护盾效果
    updateShieldEffects();
}

// 渲染游戏
function render(ctx) {
    if (!ctx || !gameState) return;
    
    // 清空画布
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
    
    // 绘制背景
    drawBackground(ctx);
    
    // 绘制玩家
    if (gameState.player) {
        drawPlayer(ctx);
    }
    
    // 绘制子弹
    if (gameState.bullets && gameState.bullets.length > 0) {
        drawBullets(ctx);
    }
    
    // 绘制敌人
    if (gameState.enemies && gameState.enemies.length > 0) {
        drawEnemies(ctx);
    }
    
    // 绘制导弹
    if (gameState.missiles && gameState.missiles.length > 0) {
        drawMissiles(ctx);
    }
    
    // 绘制激光
    if (gameState.lasers && gameState.lasers.length > 0) {
        drawLasers(ctx);
    }
    
    // 绘制粒子效果
    if (gameState.particles && gameState.particles.length > 0) {
        drawParticles(ctx);
    }
    
    // 绘制资源
    if (gameState.resources && gameState.resources.length > 0) {
        drawResources(ctx);
    }
    
    // 更新分数文字特效
    updateScoreTexts(ctx);
    
    // 绘制HUD
    updateHUD(ctx);
    
    // 渲染护盾效果
    renderShieldEffects(ctx);
}

// 设置事件监听器
function setupEventListeners() {
    // 主菜单按钮事件
    document.getElementById('btn-start-game').addEventListener('click', startGame);
    document.getElementById('btn-tutorial').addEventListener('click', showTutorial);
    document.getElementById('btn-settings').addEventListener('click', showSettings);

    // 返回主菜单按钮事件
    document.getElementById('back-to-main').addEventListener('click', backToMain);
    document.getElementById('back-to-main-2').addEventListener('click', backToMain);
    document.getElementById('back-to-main-3').addEventListener('click', backToMain);

    // 设置按钮事件
    document.getElementById('save-settings').addEventListener('click', saveSettings);

    // 暂停菜单按钮事件
    document.getElementById('resume-game').addEventListener('click', resumeGame);
    document.getElementById('settings-game').addEventListener('click', showSettings);
    document.getElementById('quit-game').addEventListener('click', quitGame);

    // 游戏结束菜单按钮事件
    document.getElementById('restart-game').addEventListener('click', restartGame);

    // 键盘事件
    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    // 鼠标事件
    const canvas = document.getElementById('game-canvas');
    if (canvas) {
        canvas.addEventListener('mousemove', handleMouseMove);
        canvas.addEventListener('mousedown', handleMouseDown);
        canvas.addEventListener('mouseup', handleMouseUp);
    }

    // 窗口大小改变事件
    window.addEventListener('resize', handleScreenResize);

    // 设置滑块事件
    const volumeSlider = document.getElementById('volume');
    const enemySpeedSlider = document.getElementById('enemy-speed');
    
    if (volumeSlider) {
        volumeSlider.addEventListener('input', (e) => {
            document.getElementById('volume-value').textContent = e.target.value;
        });
    }
    
    if (enemySpeedSlider) {
        enemySpeedSlider.addEventListener('input', (e) => {
            document.getElementById('enemy-speed-value').textContent = e.target.value;
        });
    }
}

// 处理键盘按下事件
function handleKeyDown(e) {
    if (!gameState) return;
    
    switch (e.key.toLowerCase()) {
        case 'w':
            keys.w = true;
            break;
        case 's':
            keys.s = true;
            break;
        case 'a':
            keys.a = true;
            break;
        case 'd':
            keys.d = true;
            break;
        case ' ':
            keys.space = true;
            break;
        case 'e':
            activateShield();
            break;
        case 'r':
            fireMissile();
            break;
        case 'q':
            startChargingLaser();
            break;
        case 'escape':
            togglePause();
            break;
    }
}

// 处理键盘释放事件
function handleKeyUp(e) {
    if (!gameState) return;
    
    switch (e.key.toLowerCase()) {
        case 'w':
            keys.w = false;
            break;
        case 's':
            keys.s = false;
            break;
        case 'a':
            keys.a = false;
            break;
        case 'd':
            keys.d = false;
            break;
        case ' ':
            keys.space = false;
            break;
        case 'q':
            if (gameState.player.abilities.laser.charging) {
                fireLaser();
            }
            break;
    }
}

// 修改鼠标移动事件处理函数
function handleMouseMove(e) {
    if (!gameState || !gameState.mouse) return;
    
    const canvas = document.getElementById('game-canvas');
    if (!canvas) return;
    
    const rect = canvas.getBoundingClientRect();
    gameState.mouse.x = e.clientX - rect.left;
    gameState.mouse.y = e.clientY - rect.top;
}

// 处理鼠标按下事件
function handleMouseDown(e) {
    if (!gameState || gameState.gameOver || gameState.paused) return;
    
    const canvas = document.getElementById('game-canvas');
    if (!canvas) return;
    
    const rect = canvas.getBoundingClientRect();
    gameState.mouse = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
        down: true
    };
    
    // 点击时发射一颗子弹
    shoot();
}

// 处理鼠标释放事件
function handleMouseUp(e) {
    if (!gameState.player) return;
    gameState.mouse.down = false;
}

// 开始游戏
function startGame() {
    try {
        // 隐藏所有界面
        hideAllScreens();
        
        // 获取画布
        const canvas = document.getElementById('game-canvas');
        if (canvas) {
            canvas.style.display = 'block';
        }
        
        // 初始化游戏
        initGame();
        
        // 确保游戏状态正确
        if (gameState) {
            gameState.gameOver = false;
            gameState.paused = false;
            
            // 确保所有数组都被初始化
            gameState.bullets = gameState.bullets || [];
            gameState.enemies = gameState.enemies || [];
            gameState.missiles = gameState.missiles || [];
            gameState.lasers = gameState.lasers || [];
            gameState.particles = gameState.particles || [];
            gameState.resources = gameState.resources || [];
            gameState.scoreTexts = gameState.scoreTexts || [];
        }
        
        // 设置事件监听器
        setupEventListeners();
        
    } catch (error) {
        console.error('启动游戏时出错:', error);
    }
}

// 显示教程
function showTutorial() {
    hideAllScreens();
    const tutorialMenu = document.getElementById('tutorial-menu');
    if (tutorialMenu) {
        tutorialMenu.classList.remove('hidden');
    }
}

// 显示设置
function showSettings() {
    hideAllScreens();
    const settingsMenu = document.getElementById('settings-menu');
    if (settingsMenu) {
        settingsMenu.classList.remove('hidden');
    }
}

// 恢复游戏
function resumeGame() {
    if (!gameState) return;
    
    // 隐藏暂停菜单
    const pauseMenu = document.getElementById('pause-menu');
    if (pauseMenu) {
        pauseMenu.classList.add('hidden');
    }
    
    // 恢复游戏
    gameState.paused = false;
    
    // 重新开始游戏循环
    if (!gameState.animationFrameId) {
        gameLoop();
    }
}

// 重新开始游戏
function restartGame() {
    // 隐藏游戏结束界面
    const gameOverScreen = document.getElementById('game-over');
    if (gameOverScreen) {
        gameOverScreen.classList.add('hidden');
    }
    
    // 重置游戏状态
    resetGameState();
    
    // 显示主菜单
    showMainMenu();
    
    // 停止当前游戏循环
    if (gameState && gameState.animationFrameId) {
        cancelAnimationFrame(gameState.animationFrameId);
    }
}

// 更新音量
function updateVolume(e) {
    // 更新游戏音量
}

// 更新难度
function updateDifficulty(e) {
    // 更新游戏难度
}

// 重置游戏状态
function resetGameState() {
    // 获取画布
    const canvas = document.getElementById('game-canvas');
    if (!canvas) {
        console.error('找不到游戏画布');
        return;
    }
    
    // 初始化游戏状态
    gameState = {
        player: {
            x: canvas.width / 2,
            y: canvas.height / 2,
            angle: 0,
            speed: PLAYER_SPEED,
            health: 100,
            maxHealth: 100,
            energy: 100,
            maxEnergy: 100,
            experience: 0,
            level: 1,
            score: 0,
            kills: 0,
            lastShootTime: 0,
            shootCooldown: 0.2,
            upgrades: {
                speed: 1,
                damage: 1,
                shield: 1
            },
            abilities: {
                shield: {
                    active: false,
                    cooldown: 0,
                    duration: 0,
                    maxCooldown: 8,
                    maxDuration: 5,
                    startTime: 0,
                    pulsePhase: 0
                },
                missile: {
                    cooldown: 0,
                    maxCooldown: 5
                },
                laser: {
                    charging: false,
                    chargeTime: 0,
                    cooldown: 0,
                    maxCooldown: 6
                }
            }
        },
        bullets: [],
        enemies: [],
        missiles: [],
        lasers: [],
        particles: [],
        resources: [],
        scoreTexts: [],
        mouse: {
            x: canvas.width / 2,
            y: canvas.height / 2,
            down: false
        },
        gameOver: false,
        paused: false,
        currentWave: 1
    };
}

// 修改护盾激活函数
function activateShield() {
    if (!gameState.player.abilities.shield) return;
    
    const shield = gameState.player.abilities.shield;
    if (shield.cooldown <= 0 && !shield.active) {
        shield.active = true;
        shield.duration = shield.maxDuration;
        shield.effects = [];
        shield.startTime = Date.now();
        
        // 初始化光环效果
        for (let i = 0; i < SHIELD_EFFECT_CONFIG.orbitCount; i++) {
            shield.effects.push({
                angle: (i * 2 * Math.PI) / SHIELD_EFFECT_CONFIG.orbitCount,
                radius: SHIELD_EFFECT_CONFIG.baseRadius,
                pulsePhase: 0
            });
        }
        
        createShieldActivationEffect();
    }
}

// 添加更新护盾效果的函数
function updateShieldEffects() {
    if (!gameState.player.abilities.shield || !gameState.player.abilities.shield.active) return;
    
    const shield = gameState.player.abilities.shield;
    const currentTime = Date.now();
    const elapsedTime = (currentTime - shield.startTime) / 1000;
    
    shield.effects.forEach(effect => {
        // 更新旋转角度
        effect.angle += SHIELD_EFFECT_CONFIG.orbitSpeed;
        
        // 更新脉冲效果
        effect.pulsePhase += SHIELD_EFFECT_CONFIG.pulseSpeed;
        const pulseFactor = Math.sin(effect.pulsePhase);
        effect.radius = SHIELD_EFFECT_CONFIG.baseRadius + pulseFactor * SHIELD_EFFECT_CONFIG.pulseRange;
    });
    
    // 检查护盾持续时间
    if (shield.duration <= 0) {
        shield.active = false;
        shield.effects = [];
        shield.cooldown = shield.maxCooldown;
    }
}

// 添加渲染护盾效果的函数
function renderShieldEffects(ctx) {
    if (!gameState.player.abilities.shield || !gameState.player.abilities.shield.active) return;
    
    const shield = gameState.player.abilities.shield;
    const player = gameState.player;
    
    ctx.save();
    
    // 绘制光环连接线
    ctx.beginPath();
    shield.effects.forEach((effect, index) => {
        const x = player.x + Math.cos(effect.angle) * effect.radius;
        const y = player.y + Math.sin(effect.angle) * effect.radius;
        
        if (index === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    });
    
    // 连接回第一个点
    if (shield.effects.length > 0) {
        const firstEffect = shield.effects[0];
        const x = player.x + Math.cos(firstEffect.angle) * firstEffect.radius;
        const y = player.y + Math.sin(firstEffect.angle) * firstEffect.radius;
        ctx.lineTo(x, y);
    }
    
    // 设置光环样式
    ctx.strokeStyle = SHIELD_EFFECT_CONFIG.color;
    ctx.lineWidth = 2;
    ctx.globalAlpha = 0.6;
    ctx.stroke();
    
    // 绘制光点和光晕
    shield.effects.forEach(effect => {
        const x = player.x + Math.cos(effect.angle) * effect.radius;
        const y = player.y + Math.sin(effect.angle) * effect.radius;
        
        // 绘制光晕
        const gradient = ctx.createRadialGradient(x, y, 0, x, y, 15);
        gradient.addColorStop(0, SHIELD_EFFECT_CONFIG.glowColor);
        gradient.addColorStop(1, 'rgba(0,162,255,0)');
        
        ctx.beginPath();
        ctx.fillStyle = gradient;
        ctx.globalAlpha = 0.4;
        ctx.arc(x, y, 15, 0, Math.PI * 2);
        ctx.fill();
        
        // 绘制光点
        ctx.beginPath();
        ctx.fillStyle = SHIELD_EFFECT_CONFIG.color;
        ctx.globalAlpha = 0.8;
        ctx.arc(x, y, 3, 0, Math.PI * 2);
        ctx.fill();
    });
    
    ctx.restore();
}

// 修改 resetGameState 函数中的护盾相关部分
function resetGameState() {
    // ... existing code ...
    
    gameState = {
        player: {
            // ... existing player properties ...
            abilities: {
                shield: {
                    active: false,
                    cooldown: 0,
                    duration: 0,
                    maxCooldown: 10,    // 8秒冷却时间
                    maxDuration: 10,     // 10秒持续时间
                    startTime: 0,      // 护盾激活时间
                    pulsePhase: 0      // 脉冲效果相位
                },
                // ... other abilities ...
            }
        },
        // ... rest of gameState ...
    };
    
    // ... rest of the function ...
}

// 修改 createShieldActivationEffect 函数
function createShieldActivationEffect() {
    const ctx = gameContext;
    const startRadius = 10;
    const endRadius = 50;
    const duration = 1000; // 1秒
    const startTime = Date.now();
    
    function animate() {
        const elapsed = Date.now() - startTime;
        const progress = Math.min(elapsed / duration, 1);
        
        if (progress < 1) {
            // 绘制扩散环
            const currentRadius = startRadius + (endRadius - startRadius) * progress;
            
            ctx.save();
            
            // 主扩散环
            const gradient = ctx.createRadialGradient(
                gameState.player.x, gameState.player.y, currentRadius - 5,
                gameState.player.x, gameState.player.y, currentRadius + 5
            );
            gradient.addColorStop(0, 'rgba(32, 156, 255, 0)');
            gradient.addColorStop(0.5, `rgba(32, 156, 255, ${0.8 * (1 - progress)})`);
            gradient.addColorStop(1, 'rgba(32, 156, 255, 0)');
            
            ctx.beginPath();
            ctx.arc(gameState.player.x, gameState.player.y, currentRadius, 0, Math.PI * 2);
            ctx.fillStyle = gradient;
            ctx.fill();
            
            // 能量线
            const numLines = 12;
            for (let i = 0; i < numLines; i++) {
                const angle = (Math.PI * 2 / numLines) * i;
                const lineLength = 20 * progress;
                
                ctx.beginPath();
                ctx.moveTo(
                    gameState.player.x + Math.cos(angle) * (currentRadius - lineLength),
                    gameState.player.y + Math.sin(angle) * (currentRadius - lineLength)
                );
                ctx.lineTo(
                    gameState.player.x + Math.cos(angle) * (currentRadius + lineLength),
                    gameState.player.y + Math.sin(angle) * (currentRadius + lineLength)
                );
                
                const lineGradient = ctx.createLinearGradient(
                    gameState.player.x + Math.cos(angle) * (currentRadius - lineLength),
                    gameState.player.y + Math.sin(angle) * (currentRadius - lineLength),
                    gameState.player.x + Math.cos(angle) * (currentRadius + lineLength),
                    gameState.player.y + Math.sin(angle) * (currentRadius + lineLength)
                );
                
                lineGradient.addColorStop(0, 'rgba(32, 156, 255, 0)');
                lineGradient.addColorStop(0.5, `rgba(32, 156, 255, ${0.6 * (1 - progress)})`);
                lineGradient.addColorStop(1, 'rgba(32, 156, 255, 0)');
                
                ctx.strokeStyle = lineGradient;
                ctx.lineWidth = 2;
                ctx.stroke();
            }
            
            ctx.restore();
            requestAnimationFrame(animate);
        }
    }
    
    animate();
}

// 发射导弹
function fireMissile() {
    if (!gameState || !gameState.player) return;
    
    // 检查能量和冷却
    if (gameState.player.energy < 30) {
        showMessage("能量不足！");
        return;
    }
    
    if (gameState.player.abilities.missile.cooldown > 0) {
        showMessage("导弹冷却中！");
        return;
    }
    
    // 寻找最近的敌人
    const target = findNearestEnemy();
    if (!target) {
        showMessage("没有目标！");
        return;
    }
    
    // 创建导弹
    const missile = {
        x: gameState.player.x,
        y: gameState.player.y,
        target: target,
        speed: 8,
        size: 8,
        damage: 50 + (gameState.player.upgrades.damage || 0) * 10,
        angle: Math.atan2(target.y - gameState.player.y, target.x - gameState.player.x)
    };
    
    // 初始化导弹数组
    if (!gameState.missiles) {
        gameState.missiles = [];
    }
    
    // 添加导弹
    gameState.missiles.push(missile);
    
    // 消耗能量
    gameState.player.energy -= 30;
    
    // 设置冷却
    gameState.player.abilities.missile.cooldown = 10;
    
    // 创建发射效果
    createMissileLaunchEffect(gameState.player.x, gameState.player.y);
}

// 创建导弹发射效果
function createMissileLaunchEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    // 创建发射粒子
    for (let i = 0; i < 10; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 2 + 1;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            size: Math.random() * 3 + 2,
            life: 1,
            color: '#ff8800'
        };
        gameState.particles.push(particle);
    }
}

// 显示消息
function showMessage(text) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'game-message';
    messageDiv.textContent = text;
    document.body.appendChild(messageDiv);
    
    setTimeout(() => {
        messageDiv.remove();
    }, 2000);
}

// 寻找最近的敌人
function findNearestEnemy() {
    if (!gameState || !gameState.enemies || !gameState.player) return null;

    let nearestEnemy = null;
    let minDistance = Infinity;

    gameState.enemies.forEach(enemy => {
        const dx = enemy.x - gameState.player.x;
        const dy = enemy.y - gameState.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < minDistance) {
            minDistance = distance;
            nearestEnemy = enemy;
        }
    });

    return nearestEnemy;
}

// 增强的导弹发射特效
function createEnhancedMissileLaunchEffect(missile) {
    // 创建爆炸式粒子
    for (let i = 0; i < 30; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 5 + 2;
        const particle = {
            x: missile.x,
            y: missile.y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            life: 1,
            size: Math.random() * 3 + 2,
            color: `hsl(${Math.random() * 60 + 20}, 100%, 50%)` // 橙色到黄色的随机色
        };
        missile.particles.push(particle);
    }
    
    // 创建冲击波效果
    const shockwave = {
        x: missile.x,
        y: missile.y,
        radius: 0,
        maxRadius: 40,
        life: 1
    };
    if (!gameState.shockwaves) {
        gameState.shockwaves = [];
    }
    gameState.shockwaves.push(shockwave);
}

// 更新导弹状态
function updateMissiles() {
    if (!gameState || !gameState.missiles) return;

    for (let i = gameState.missiles.length - 1; i >= 0; i--) {
        const missile = gameState.missiles[i];
        
        // 如果目标不存在，移除导弹
        if (!missile.target || !gameState.enemies.includes(missile.target)) {
            gameState.missiles.splice(i, 1);
            continue;
        }

        // 计算到目标的角度
        const targetAngle = Math.atan2(
            missile.target.y - missile.y,
            missile.target.x - missile.x
        );

        // 更新导弹位置
        missile.x += Math.cos(missile.angle) * missile.speed;
        missile.y += Math.sin(missile.angle) * missile.speed;

        // 检查碰撞
        const dx = missile.target.x - missile.x;
        const dy = missile.target.y - missile.y;
        const distance = Math.sqrt(dx * dx + dy * dy);

        if (distance < missile.size + missile.target.size) {
            // 命中目标
            missile.target.health -= missile.damage;
            createExplosionEffect(missile.x, missile.y);
            gameState.missiles.splice(i, 1);
            
            // 如果敌人被消灭
            if (missile.target.health <= 0) {
                const enemyIndex = gameState.enemies.indexOf(missile.target);
                if (enemyIndex > -1) {
                    gameState.enemies.splice(enemyIndex, 1);
                    addScore(50);
                    addExperience(5);
                }
            }
        }
    }

    // 绘制导弹
    if (gameContext) {
        gameState.missiles.forEach(missile => {
            gameContext.save();
            gameContext.translate(missile.x, missile.y);
            gameContext.rotate(missile.angle);
            
            // 绘制导弹主体
            gameContext.fillStyle = '#ff4400';
            gameContext.beginPath();
            gameContext.moveTo(missile.size, 0);
            gameContext.lineTo(-missile.size, missile.size/2);
            gameContext.lineTo(-missile.size, -missile.size/2);
            gameContext.closePath();
            gameContext.fill();
            
            // 绘制尾焰
            gameContext.fillStyle = '#ff8800';
            gameContext.beginPath();
            gameContext.moveTo(-missile.size, 0);
            gameContext.lineTo(-missile.size * 2, missile.size/3);
            gameContext.lineTo(-missile.size * 2, -missile.size/3);
            gameContext.closePath();
            gameContext.fill();
            
            gameContext.restore();
        });
    }
}

// 创建爆炸特效
function createExplosionEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }

    // 创建爆炸粒子
    for (let i = 0; i < 20; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 3 + 2;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            size: Math.random() * 3 + 2,
            life: 1,
            color: Math.random() < 0.5 ? '#ff4400' : '#ff8800'
        };
        gameState.particles.push(particle);
    }
}

// 更新敌人子弹
function updateEnemyProjectiles(enemy) {
    if (!enemy || !gameState.player) return;
    
    const currentTime = Date.now();
    if (currentTime - enemy.lastShootTime < enemy.shootCooldown * 1000) return;
    
    // 计算到玩家的角度
    const angle = Math.atan2(
        gameState.player.y - enemy.y,
        gameState.player.x - enemy.x
    );
    
    // 创建子弹
    const bullet = {
        x: enemy.x,
        y: enemy.y,
        angle: angle,
        speed: ENEMY_PROJECTILE_SPEED,
        damage: enemy.damage || 10,
        size: ENEMY_BULLET_SIZE,
        velocity: {
            x: Math.cos(angle) * ENEMY_PROJECTILE_SPEED,
            y: Math.sin(angle) * ENEMY_PROJECTILE_SPEED
        },
        creationTime: currentTime,
        lifeTime: 3000 // 敌人子弹存活3秒
    };
    
    if (!gameState.enemyBullets) {
        gameState.enemyBullets = [];
    }
    
    gameState.enemyBullets.push(bullet);
    enemy.lastShootTime = currentTime;
    
    createEnemyShootingEffect(enemy.x, enemy.y, angle);
}

// 创建玩家射击特效
function createShootingEffect(x, y, angle) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    // 创建枪口闪光效果
    for (let i = 0; i < 5; i++) {
        const spread = (Math.random() - 0.5) * 0.5;
        const speed = Math.random() * 3 + 2;
        
        gameState.particles.push({
            x: x,
            y: y,
            vx: Math.cos(angle + spread) * speed,
            vy: Math.sin(angle + spread) * speed,
            size: Math.random() * 2 + 1,
            life: 0.5,
            color: 'rgba(0, 255, 136, 0.8)'
        });
    }
}

// 创建敌人射击特效
function createEnemyShootingEffect(x, y, angle) {
    for (let i = 0; i < 8; i++) {
        const spread = (Math.random() - 0.5) * Math.PI / 4;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle + spread) * 5,
            vy: Math.sin(angle + spread) * 5,
            life: 20,
            color: '#ff4444',
            size: Math.random() * 2 + 1
        };
        gameState.particles.push(particle);
    }
}

// 创建击中特效
function createHitEffect(x, y, color = 'rgba(0, 255, 136, 0.8)') {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    // 创建多个粒子形成爆炸效果
    for (let i = 0; i < 8; i++) {
        const angle = (Math.PI * 2 / 8) * i;
        const speed = Math.random() * 2 + 2;
        
        gameState.particles.push({
            x: x,
            y: y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            size: Math.random() * 2 + 1,
            life: 1,
            color: color
        });
    }
}

// 修改 updateBullets 函数
function updateBullets() {
    if (!gameState.bullets) return;
    
    const currentTime = Date.now();
    gameState.bullets = gameState.bullets.filter(bullet => {
        // 检查子弹生存时间
        if (currentTime - bullet.creationTime > bullet.lifeTime) {
            return false;
        }
        
        // 更新子弹位置
        bullet.x += bullet.velocity.x;
        bullet.y += bullet.velocity.y;
        
        // 检查是否超出边界
        if (bullet.x < 0 || bullet.x > GAME_WIDTH || 
            bullet.y < 0 || bullet.y > GAME_HEIGHT) {
            return false;
        }
        
        // 寻找最近的敌人进行追踪
        if (bullet.tracking) {
            const nearestEnemy = findNearestEnemyToBullet(bullet);
            if (nearestEnemy) {
                // 计算到目标的角度
                const targetAngle = Math.atan2(
                    nearestEnemy.y - bullet.y,
                    nearestEnemy.x - bullet.x
                );
                
                // 计算当前速度角度
                const currentAngle = Math.atan2(bullet.velocity.y, bullet.velocity.x);
                
                // 计算角度差
                let angleDiff = targetAngle - currentAngle;
                while (angleDiff > Math.PI) angleDiff -= Math.PI * 2;
                while (angleDiff < -Math.PI) angleDiff += Math.PI * 2;
                
                // 平滑转向
                const turnAmount = Math.min(
                    Math.abs(angleDiff),
                    BULLET_CONFIG.turnSpeed
                ) * Math.sign(angleDiff);
                
                // 更新速度方向
                const newAngle = currentAngle + turnAmount;
                bullet.velocity.x = Math.cos(newAngle) * BULLET_CONFIG.speed;
                bullet.velocity.y = Math.sin(newAngle) * BULLET_CONFIG.speed;
                
                // 更新子弹角度（用于渲染）
                bullet.angle = newAngle;
            }
        }
        
        return true;
    });
}

// 修改寻找最近敌人函数
function findNearestEnemyToBullet(bullet) {
    if (!gameState.enemies || gameState.enemies.length === 0) return null;
    
    let nearestEnemy = null;
    let nearestDistance = BULLET_CONFIG.maxTrackingRange;
    
    gameState.enemies.forEach(enemy => {
        const dx = enemy.x - bullet.x;
        const dy = enemy.y - bullet.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestEnemy = enemy;
        }
    });
    
    return nearestEnemy;
}

// 更新粒子效果
function updateParticles() {
    if (!gameState.particles || !gameContext) return;
    
    for (let i = gameState.particles.length - 1; i >= 0; i--) {
        const particle = gameState.particles[i];
        
        // 更新粒子位置
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.life -= 0.02;
        
        // 绘制粒子
        gameContext.save();
        gameContext.globalAlpha = particle.life / 30;
        gameContext.fillStyle = particle.color;
        gameContext.shadowColor = particle.color;
        gameContext.shadowBlur = 10;
        
        gameContext.beginPath();
        gameContext.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        gameContext.fill();
        
        gameContext.restore();
        
        // 移除死亡的粒子
        if (particle.life <= 0) {
            gameState.particles.splice(i, 1);
        }
    }
}

// 更新技能冷却
function updateAbilities() {
    if (!gameState || !gameState.player || !gameState.player.abilities) return;
    
    try {
        const abilities = gameState.player.abilities;
        const deltaTime = 0.016; // 假设60fps
        
        // 更新护盾
        if (abilities.shield) {
            if (abilities.shield.active) {
                abilities.shield.duration -= deltaTime;
                if (abilities.shield.duration <= 0) {
                    abilities.shield.active = false;
                    abilities.shield.cooldown = abilities.shield.maxCooldown;
                }
            } else if (abilities.shield.cooldown > 0) {
                abilities.shield.cooldown -= deltaTime;
            }
        }
        
        // 更新导弹
        if (abilities.missile && abilities.missile.cooldown > 0) {
            abilities.missile.cooldown -= deltaTime;
        }
        
        // 更新激光
        if (abilities.laser) {
            if (abilities.laser.cooldown > 0) {
                abilities.laser.cooldown -= deltaTime;
            }
            
            if (abilities.laser.charging) {
                abilities.laser.chargeTime = Math.min(abilities.laser.chargeTime + deltaTime, 2);
                gameState.player.energy = Math.max(0, gameState.player.energy - 25 * deltaTime);
                
                if (gameState.player.energy <= 0) {
                    fireLaser();
                }
            }
        }
        
        // 更新技能图标显示
        updateAbilityIcons();
        
    } catch (error) {
        console.error('更新技能时出错:', error);
    }
}

// 检查碰撞
function checkCollisions() {
    if (!gameState || !gameState.player) return;
    
    // 确保所有必要的数组都已初始化
    if (!gameState.bullets) gameState.bullets = [];
    if (!gameState.enemies) gameState.enemies = [];
    if (!gameState.enemyBullets) gameState.enemyBullets = [];
    
    // 玩家子弹击中敌人
    for (let i = gameState.bullets.length - 1; i >= 0; i--) {
        const bullet = gameState.bullets[i];
        for (let j = gameState.enemies.length - 1; j >= 0; j--) {
            const enemy = gameState.enemies[j];
            const dx = bullet.x - enemy.x;
            const dy = bullet.y - enemy.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < enemy.size + bullet.size) {
                // 敌人受到伤害
                enemy.health -= bullet.damage;
                createHitEffect(bullet.x, bullet.y, 'rgba(255, 0, 0, 0.8)');
                
                // 移除子弹
                gameState.bullets.splice(i, 1);
                
                // 如果敌人死亡
                if (enemy.health <= 0) {
                    gameState.enemies.splice(j, 1);
                    if (gameState.player) {
                        gameState.player.score = (gameState.player.score || 0) + 100;
                        gameState.player.kills = (gameState.player.kills || 0) + 1;
                    }
                    createExplosionEffect(enemy.x, enemy.y);
                    addExperience(10);
                }
                break;
            }
        }
    }
    
    // 敌人子弹击中玩家
    for (let i = gameState.enemyBullets.length - 1; i >= 0; i--) {
        const bullet = gameState.enemyBullets[i];
        const dx = bullet.x - gameState.player.x;
        const dy = bullet.y - gameState.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < gameState.player.size + bullet.size) {
            // 检查玩家是否有护盾
            if (!gameState.player.abilities?.shield?.active) {
                // 玩家受到伤害
                gameState.player.health -= bullet.damage;
                createHitEffect(bullet.x, bullet.y, 'rgba(255, 0, 0, 0.8)');
                
                // 检查玩家是否死亡
                if (gameState.player.health <= 0) {
                    gameOver();
                }
            }
            
            // 移除子弹
            gameState.enemyBullets.splice(i, 1);
        }
    }
}

// 游戏结束
function gameOver() {
    if (!gameState) return;
    
    // 设置游戏结束状态
    gameState.gameOver = true;
    gameState.paused = true;
    
    // 清空所有游戏对象
    gameState.enemies = [];
    gameState.bullets = [];
    gameState.missiles = [];
    gameState.lasers = [];
    gameState.particles = [];
    gameState.resources = [];
    
    // 停止所有动画和更新
    cancelAnimationFrame(gameState.animationFrameId);
    
    // 显示游戏结束界面
    const gameOverScreen = document.getElementById('game-over');
    if (gameOverScreen) {
        gameOverScreen.classList.remove('hidden');
        
        // 更新最终统计数据
        document.getElementById('final-score').textContent = gameState.player.score || 0;
        document.getElementById('final-wave').textContent = gameState.currentWave || 1;
        document.getElementById('final-kills').textContent = gameState.player.kills || 0;
    }
}

// 切换暂停状态
function togglePause() {
    if (!gameState) return;
    
    const pauseMenu = document.getElementById('pause-menu');
    if (!pauseMenu) return;
    
    if (gameState.paused) {
        // 恢复游戏
        pauseMenu.classList.add('hidden');
        gameState.paused = false;
        if (!gameState.animationFrameId) {
            gameLoop();
        }
    } else {
        // 暂停游戏
        pauseMenu.classList.remove('hidden');
        gameState.paused = true;
    }
}

// 绘制背景
function drawBackground(ctx) {
    if (!ctx) return;
    
    // 绘制深色背景
    ctx.fillStyle = '#000033';
    ctx.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);
    
    // 绘制星星
    for (let i = 0; i < 100; i++) {
        const x = Math.random() * GAME_WIDTH;
        const y = Math.random() * GAME_HEIGHT;
        const size = Math.random() * 2;
        
        ctx.fillStyle = 'rgba(255, 255, 255, ' + (Math.random() * 0.5 + 0.5) + ')';
        ctx.beginPath();
        ctx.arc(x, y, size, 0, Math.PI * 2);
        ctx.fill();
    }
}

// 绘制玩家
function drawPlayer(ctx) {
    const x = gameState.player.x;
    const y = gameState.player.y;
    const angle = gameState.player.angle;

    ctx.save();
    ctx.translate(x, y);
    ctx.rotate(angle);

    // 绘制飞船主体
    ctx.beginPath();
    ctx.moveTo(25, 0);
    ctx.lineTo(-15, -15);
    ctx.lineTo(-8, 0);
    ctx.lineTo(-15, 15);
    ctx.closePath();

    // 创建渐变
    const gradient = ctx.createLinearGradient(-15, 0, 25, 0);
    gradient.addColorStop(0, '#00ff88');
    gradient.addColorStop(1, '#00b8ff');
    ctx.fillStyle = gradient;
    ctx.fill();

    // 添加发光效果
    ctx.shadowColor = '#00ff88';
    ctx.shadowBlur = 10;
    ctx.strokeStyle = '#fff';
    ctx.lineWidth = 1;
    ctx.stroke();

    // 绘制引擎效果
    ctx.beginPath();
    ctx.moveTo(-15, -8);
    ctx.lineTo(-25, 0);
    ctx.lineTo(-15, 8);

    const engineGlow = ctx.createLinearGradient(-25, 0, -15, 0);
    engineGlow.addColorStop(0, 'rgba(255, 100, 0, 0)');
    engineGlow.addColorStop(1, 'rgba(255, 100, 0, 0.8)');
    ctx.fillStyle = engineGlow;
    ctx.fill();

    ctx.restore();
}

// 绘制资源
function drawResources(ctx) {
    gameState.resources.forEach(resource => {
        let color;
        switch (resource.type) {
            case 'energy':
                color = '#00b8ff';
                break;
            case 'health':
                color = '#ff4444';
                break;
            case 'upgrade':
                color = '#00ff88';
                break;
        }

        ctx.fillStyle = color;
        ctx.beginPath();
        ctx.arc(resource.x, resource.y, resource.size, 0, Math.PI * 2);
        ctx.fill();

        // 添加闪光效果
        ctx.strokeStyle = 'white';
        ctx.lineWidth = 2;
        ctx.stroke();
    });
}

// 绘制敌人
function drawEnemies(ctx) {
    gameState.enemies.forEach(enemy => {
        ctx.save();
        ctx.translate(enemy.x, enemy.y);

        // 计算朝向玩家的角度
        enemy.angle = Math.atan2(
            gameState.player.y - enemy.y,
            gameState.player.x - enemy.x
        );
        ctx.rotate(enemy.angle);

        // 绘制敌人飞船
        ctx.beginPath();
        ctx.moveTo(15, 0);
        ctx.lineTo(-10, -10);
        ctx.lineTo(-5, 0);
        ctx.lineTo(-10, 10);
        ctx.closePath();

        // 创建渐变
        const gradient = ctx.createLinearGradient(-10, 0, 15, 0);
        gradient.addColorStop(0, '#ff0000');
        gradient.addColorStop(1, '#ff4444');
        ctx.fillStyle = gradient;
        ctx.fill();

        // 添加发光效果
        ctx.shadowColor = '#ff0000';
        ctx.shadowBlur = 10;
        ctx.strokeStyle = '#fff';
        ctx.lineWidth = 1;
        ctx.stroke();

        // 绘制生命值条
        const healthBarWidth = 40;
        const healthBarHeight = 4;
        const healthPercentage = enemy.health / (20 + (gameState.player.level * 5));

        ctx.rotate(-enemy.angle); // 取消旋转以绘制水平生命值条

        // 生命值条背景
        ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
        ctx.fillRect(-healthBarWidth / 2, -25, healthBarWidth, healthBarHeight);

        // 生命值条
        const healthGradient = ctx.createLinearGradient(-healthBarWidth / 2, 0, healthBarWidth / 2, 0);
        healthGradient.addColorStop(0, '#ff0000');
        healthGradient.addColorStop(1, '#ff4444');
        ctx.fillStyle = healthGradient;
        ctx.fillRect(-healthBarWidth / 2, -25, healthBarWidth * healthPercentage, healthBarHeight);

        ctx.restore();
    });
}

// 绘制子弹
function drawBullets(ctx) {
    if (!ctx || !gameState || !gameState.bullets) return;
    
    ctx.save();
    
    gameState.bullets.forEach(bullet => {
        // 绘制子弹主体
        ctx.beginPath();
        ctx.arc(bullet.x, bullet.y, bullet.size, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(0, 255, 136, 0.8)';
        ctx.fill();
        
        // 添加发光效果
        ctx.shadowColor = 'rgba(0, 255, 136, 0.5)';
        ctx.shadowBlur = 10;
        ctx.fill();
        
        // 绘制子弹尾迹
        ctx.beginPath();
        ctx.moveTo(bullet.x, bullet.y);
        ctx.lineTo(
            bullet.x - Math.cos(bullet.angle) * 10,
            bullet.y - Math.sin(bullet.angle) * 10
        );
        ctx.strokeStyle = 'rgba(0, 255, 136, 0.3)';
        ctx.lineWidth = bullet.size;
        ctx.stroke();
    });
    
    ctx.restore();
}

// 绘制激光
function drawLasers(ctx) {
    if (!gameState.lasers || !gameContext) return;
    
    for (let i = gameState.lasers.length - 1; i >= 0; i--) {
        const laser = gameState.lasers[i];
        
        // 绘制激光
        gameContext.save();
        
        // 创建激光渐变
        const gradient = gameContext.createLinearGradient(
            laser.startX,
            laser.startY,
            laser.startX + Math.cos(laser.angle) * laser.length,
            laser.startY + Math.sin(laser.angle) * laser.length
        );
        
        const alpha = laser.life / laser.maxLife;
        gradient.addColorStop(0, `rgba(0, 231, 255, ${alpha})`);
        gradient.addColorStop(0.5, `rgba(0, 231, 255, ${alpha * 0.8})`);
        gradient.addColorStop(1, `rgba(0, 231, 255, 0)`);
        
        // 绘制激光主体
        gameContext.beginPath();
        gameContext.moveTo(laser.startX, laser.startY);
        gameContext.lineTo(
            laser.startX + Math.cos(laser.angle) * laser.length,
            laser.startY + Math.sin(laser.angle) * laser.length
        );
        
        gameContext.strokeStyle = gradient;
        gameContext.lineWidth = laser.width * (laser.life / laser.maxLife);
        gameContext.lineCap = 'round';
        
        // 添加发光效果
        gameContext.shadowColor = 'rgba(0, 231, 255, 0.5)';
        gameContext.shadowBlur = 20;
        gameContext.stroke();
        
        // 检测碰撞
        if (gameState.enemies) {
            for (let j = gameState.enemies.length - 1; j >= 0; j--) {
                const enemy = gameState.enemies[j];
                
                // 计算敌人到激光的距离
                const dx = enemy.x - laser.startX;
                const dy = enemy.y - laser.startY;
                const laserDx = Math.cos(laser.angle);
                const laserDy = Math.sin(laser.angle);
                
                // 计算投影距离
                const projection = dx * laserDx + dy * laserDy;
                const projectionPoint = {
                    x: laser.startX + laserDx * projection,
                    y: laser.startY + laserDy * projection
                };
                
                // 检查投影点是否在激光范围内
                if (projection >= 0 && projection <= laser.length) {
                    const distanceToLaser = Math.sqrt(
                        Math.pow(enemy.x - projectionPoint.x, 2) +
                        Math.pow(enemy.y - projectionPoint.y, 2)
                    );
                    
                    if (distanceToLaser <= enemy.size + laser.width / 2) {
                        // 造成伤害
                        enemy.health -= laser.damage * 0.016; // 每帧伤害
                        
                        // 创建命中特效
                        createLaserHitEffect(enemy.x, enemy.y);
                        
                        // 检查敌人是否死亡
                        if (enemy.health <= 0) {
                            gameState.enemies.splice(j, 1);
                            gameState.player.score += 100;
                            gameState.player.kills++;
                            addExperience(10);
                        }
                    }
                }
            }
        }
        
        gameContext.restore();
    }
}

// 添加激光命中特效函数
function createLaserHitEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    // 创建粒子效果
    for (let i = 0; i < 3; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 2 + 1;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            life: 0.5,
            size: Math.random() * 3 + 2,
            color: 'rgba(0, 231, 255, 0.8)'
        };
        
        gameState.particles.push(particle);
    }
}

// 修改 findNearestEnemy 函数
function findNearestEnemy() {
    if (!gameState.player || !gameState.enemies || gameState.enemies.length === 0) return null;
    
    let nearestEnemy = null;
    let nearestDistance = Infinity;
    
    gameState.enemies.forEach(enemy => {
        const dx = enemy.x - gameState.player.x;
        const dy = enemy.y - gameState.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance < nearestDistance) {
            nearestDistance = distance;
            nearestEnemy = enemy;
        }
    });
    
    return nearestEnemy;
}

// 添加 updateLasers 函数
function updateLasers() {
    if (!gameState.lasers || !gameContext) return;
    
    for (let i = gameState.lasers.length - 1; i >= 0; i--) {
        const laser = gameState.lasers[i];
        
        // 更新激光生命周期
        laser.life -= 0.016;
        
        if (laser.life <= 0) {
            gameState.lasers.splice(i, 1);
            continue;
        }
        
        // 绘制激光
        gameContext.save();
        
        // 创建激光渐变
        const gradient = gameContext.createLinearGradient(
            laser.startX,
            laser.startY,
            laser.startX + Math.cos(laser.angle) * laser.length,
            laser.startY + Math.sin(laser.angle) * laser.length
        );
        
        const alpha = laser.life / laser.maxLife;
        gradient.addColorStop(0, `rgba(0, 231, 255, ${alpha})`);
        gradient.addColorStop(0.5, `rgba(0, 231, 255, ${alpha * 0.8})`);
        gradient.addColorStop(1, `rgba(0, 231, 255, 0)`);
        
        // 绘制激光主体
        gameContext.beginPath();
        gameContext.moveTo(laser.startX, laser.startY);
        gameContext.lineTo(
            laser.startX + Math.cos(laser.angle) * laser.length,
            laser.startY + Math.sin(laser.angle) * laser.length
        );
        
        gameContext.strokeStyle = gradient;
        gameContext.lineWidth = laser.width * (laser.life / laser.maxLife);
        gameContext.lineCap = 'round';
        
        // 添加发光效果
        gameContext.shadowColor = 'rgba(0, 231, 255, 0.5)';
        gameContext.shadowBlur = 20;
        gameContext.stroke();
        
        // 检测碰撞
        if (gameState.enemies) {
            for (let j = gameState.enemies.length - 1; j >= 0; j--) {
                const enemy = gameState.enemies[j];
                
                // 计算敌人到激光的距离
                const dx = enemy.x - laser.startX;
                const dy = enemy.y - laser.startY;
                const laserDx = Math.cos(laser.angle);
                const laserDy = Math.sin(laser.angle);
                
                // 计算投影距离
                const projection = dx * laserDx + dy * laserDy;
                const projectionPoint = {
                    x: laser.startX + laserDx * projection,
                    y: laser.startY + laserDy * projection
                };
                
                // 检查投影点是否在激光范围内
                if (projection >= 0 && projection <= laser.length) {
                    const distanceToLaser = Math.sqrt(
                        Math.pow(enemy.x - projectionPoint.x, 2) +
                        Math.pow(enemy.y - projectionPoint.y, 2)
                    );
                    
                    if (distanceToLaser <= enemy.size + laser.width / 2) {
                        // 造成伤害
                        enemy.health -= laser.damage * 0.016; // 每帧伤害
                        
                        // 创建命中特效
                        createLaserHitEffect(enemy.x, enemy.y);
                        
                        // 检查敌人是否死亡
                        if (enemy.health <= 0) {
                            gameState.enemies.splice(j, 1);
                            gameState.player.score += 100;
                            gameState.player.kills++;
                            addExperience(10);
                        }
                    }
                }
            }
        }
        
        gameContext.restore();
    }
}

// 添加激光命中特效函数
function createLaserHitEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    // 创建粒子效果
    for (let i = 0; i < 3; i++) {
        const angle = Math.random() * Math.PI * 2;
        const speed = Math.random() * 2 + 1;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * speed,
            vy: Math.sin(angle) * speed,
            life: 0.5,
            size: Math.random() * 3 + 2,
            color: 'rgba(0, 231, 255, 0.8)'
        };
        
        gameState.particles.push(particle);
    }
}

// 修改 update 函数中的激光更新部分
function update() {
    if (!gameState || gameState.gameOver || gameState.paused) {
        return;
    }
    
    // 更新玩家
    updatePlayer();
    
    // 更新子弹
    if (gameState.bullets && gameState.bullets.length > 0) {
        updateBullets();
    }
    
    // 更新敌人
    if (gameState.enemies && gameState.enemies.length > 0) {
        updateEnemies();
    }
    
    // 更新导弹
    if (gameState.missiles && gameState.missiles.length > 0) {
        updateMissiles();
    }
    
    // 更新激光
    if (gameState.lasers && gameState.lasers.length > 0) {
        updateLasers();
    }
    
    // 更新粒子效果
    if (gameState.particles && gameState.particles.length > 0) {
        updateParticles();
    }
    
    // 更新资源
    if (gameState.resources && gameState.resources.length > 0) {
        updateResources();
    }
    
    // 检查碰撞
    checkCollisions();
    
    // 生成新资源
    if (Math.random() < RESOURCE_SPAWN_RATE) {
        spawnResource();
    }
    
    // 生成新敌人
    if (Math.random() < ENEMY_SPAWN_RATE && gameState.enemies.length < 5) {
        spawnEnemy();
    }
    
    // 更新技能图标
    updateAbilityIcons();
    
    // 更新技能冷却
    updateAbilities();
    
    // 更新护盾效果
    updateShieldEffects();
}

// 添加界面管理相关函数
function hideAllScreens() {
    const screens = [
        'main-menu',
        'tutorial-menu',
        'settings-menu',
        'pause-menu',
        'game-over'
    ];
    
    screens.forEach(screenId => {
        const screen = document.getElementById(screenId);
        if (screen) {
            screen.classList.add('hidden');
        }
    });
}

function showMainMenu() {
    hideAllScreens();
    const mainMenu = document.getElementById('main-menu');
    if (mainMenu) {
        mainMenu.classList.remove('hidden');
    }
}

function showTutorial() {
    hideAllScreens();
    const tutorialMenu = document.getElementById('tutorial-menu');
    if (tutorialMenu) {
        tutorialMenu.classList.remove('hidden');
    }
}

function showSettings() {
    hideAllScreens();
    const settingsMenu = document.getElementById('settings-menu');
    if (settingsMenu) {
        settingsMenu.classList.remove('hidden');
    }
}

// 修改 initGame 函数
function initGame() {
    try {
        // 获取画布和上下文
        const canvas = document.getElementById('game-canvas');
        if (!canvas) {
            console.error('找不到游戏画布');
            return;
        }
        
        // 设置画布大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        GAME_WIDTH = window.innerWidth;
        GAME_HEIGHT = window.innerHeight;
        
        // 获取绘图上下文
        const ctx = canvas.getContext('2d');
        if (!ctx) {
            console.error('无法获取画布上下文');
            return;
        }
        
        // 设置全局游戏上下文
        gameContext = ctx;
        
        // 初始化按键状态
        keys = {
            w: false,
            s: false,
            a: false,
            d: false,
            space: false
        };
        
        // 初始化游戏状态
        gameState = {
            player: {
                x: canvas.width / 2,
                y: canvas.height / 2,
                angle: 0,
                speed: PLAYER_SPEED,
                health: 100,
                maxHealth: 100,
                energy: 100,
                maxEnergy: 100,
                experience: 0,
                level: 1,
                score: 0,
                kills: 0,
                lastShootTime: 0,
                shootCooldown: 0.2,
                upgrades: {
                    speed: 1,
                    damage: 1,
                    shield: 1
                },
                abilities: {
                    shield: {
                        active: false,
                        cooldown: 0,
                        duration: 0,
                        maxCooldown: 8,
                        maxDuration: 5,
                        startTime: 0,
                        pulsePhase: 0
                    },
                    missile: {
                        cooldown: 0,
                        maxCooldown: 5
                    },
                    laser: {
                        charging: false,
                        chargeTime: 0,
                        cooldown: 0,
                        maxCooldown: 6
                    }
                }
            },
            bullets: [],
            enemies: [],
            missiles: [],
            lasers: [],
            particles: [],
            resources: [],
            scoreTexts: [],
            mouse: {
                x: canvas.width / 2,
                y: canvas.height / 2,
                down: false
            },
            gameOver: false,
            paused: false,
            currentWave: 1
        };
        
        // 设置事件监听器
        setupEventListeners();
        
        // 开始游戏循环
        gameLoop();
        
        // 初始化技能图标
        updateAbilityIcons();
        
    } catch (error) {
        console.error('初始化游戏时出错:', error);
    }
}

// 添加DOMContentLoaded事件监听器
document.addEventListener('DOMContentLoaded', () => {
    try {
        // 设置事件监听
        setupEventListeners();
        
        // 初始化游戏
        initGame();
        
        // 显示主菜单
        showMainMenu();
    } catch (error) {
        console.error('初始化游戏时发生错误:', error);
    }
});

// 添加屏幕大小调整处理函数
function handleScreenResize() {
    const canvas = document.getElementById('game-canvas');
    if (!canvas) return;
    
    // 设置画布大小为窗口大小
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    // 如果游戏状态存在，更新玩家位置到新的中心点
    if (gameState && gameState.player) {
        gameState.player.x = canvas.width / 2;
        gameState.player.y = canvas.height / 2;
    }
}

// 添加激光充能更新函数
function updateLaserCharging() {
    if (!gameState.player || !gameState.player.abilities) return;
    
    const laser = gameState.player.abilities.laser;
    if (!laser.charging) return;
    
    // 更新充能时间
    laser.chargeTime = Math.min(laser.chargeTime + 0.016, 2);
    
    // 消耗能量
    gameState.player.energy = Math.max(0, gameState.player.energy - 25 * 0.016);
    
    // 如果能量不足，自动发射
    if (gameState.player.energy <= 0) {
        fireLaser();
        return;
    }
    
    // 创建充能特效
    createChargingEffect();
}

// 修改createChargingEffect函数
function createChargingEffect() {
    if (!gameState.player || !gameState.player.abilities) return;
    
    const laser = gameState.player.abilities.laser;
    const chargeRatio = laser.chargeTime / 2;
    const chargeRadius = 30 + chargeRatio * 20;
    
    // 创建充能粒子
    for (let i = 0; i < 3; i++) {
        const angle = Math.random() * Math.PI * 2;
        const distance = Math.random() * chargeRadius;
        const particle = {
            x: gameState.player.x + Math.cos(angle) * distance,
            y: gameState.player.y + Math.sin(angle) * distance,
            vx: (Math.random() - 0.5) * 2,
            vy: (Math.random() - 0.5) * 2,
            life: 0.5,
            size: Math.random() * 3 + 2,
            color: `rgba(0, ${360 + chargeRatio * 75}, 255, ${0.5 + chargeRatio * 0.5})`
        };
        
        if (!gameState.chargingParticles) {
            gameState.chargingParticles = [];
        }
        gameState.chargingParticles.push(particle);
    }
}

// 修改 activateShield 函数
function activateShield() {
    if (!gameState.player.abilities.shield) return;
    
    const shield = gameState.player.abilities.shield;
    if (shield.cooldown <= 0 && !shield.active) {
        shield.active = true;
        shield.duration = shield.maxDuration;
        shield.effects = [];
        shield.startTime = Date.now();
        
        // 初始化光环效果
        for (let i = 0; i < SHIELD_EFFECT_CONFIG.orbitCount; i++) {
            shield.effects.push({
                angle: (i * 2 * Math.PI) / SHIELD_EFFECT_CONFIG.orbitCount,
                radius: SHIELD_EFFECT_CONFIG.baseRadius,
                pulsePhase: 0
            });
        }
        
        createShieldActivationEffect();
    }
}

// 修改 startChargingLaser 函数
function startChargingLaser() {
    if (!gameState.player || !gameState.player.abilities) return;
    
    const laser = gameState.player.abilities.laser;
    if (laser.cooldown > 0 || laser.charging || gameState.player.energy < 10) return;
    
    laser.charging = true;
    laser.chargeTime = 0;
    
    // 初始化充能粒子数组
    if (!gameState.chargingParticles) {
        gameState.chargingParticles = [];
    }
}

// 修改 fireLaser 函数
function fireLaser() {
    if (!gameState || !gameState.player || !gameState.player.abilities || !gameContext) return;
    
    const laser = gameState.player.abilities.laser;
    if (!laser.charging) return;
    
    // 计算激光伤害和宽度
    const chargeRatio = Math.min(laser.chargeTime / 2, 1);
    const damage = 150 + chargeRatio * 200;  // 提高激光伤害
    const width = 5 + chargeRatio * 15;
    
    // 创建激光对象
    const newLaser = {
        startX: gameState.player.x,
        startY: gameState.player.y,
        angle: gameState.player.angle,
        length: 1000,
        width: width,
        damage: damage,
        life: 1,
        maxLife: 0.5
    };
    
    if (!gameState.lasers) {
        gameState.lasers = [];
    }
    
    gameState.lasers.push(newLaser);
    
    // 重置激光状态
    laser.charging = false;
    laser.chargeTime = 0;
    laser.cooldown = laser.maxCooldown;
    
    // 清除充能粒子
    gameState.chargingParticles = [];
}

// 返回主菜单函数
function backToMain() {
    // 如果游戏正在运行，停止游戏循环
    if (gameState && gameState.animationFrameId) {
        cancelAnimationFrame(gameState.animationFrameId);
    }
    
    // 重置游戏状态
    gameState = null;
    gameContext = null;
    
    // 隐藏所有界面
    hideAllScreens();
    
    // 显示主菜单
    document.getElementById('main-menu').classList.remove('hidden');
}

// 更新技能图标状态
function updateAbilityIcons() {
    if (!gameState || !gameState.player || !gameState.player.abilities) return;
    
    try {
        const abilities = gameState.player.abilities;
        
        // 更新护盾图标
        const shieldIcon = document.getElementById('shield-ability');
        if (shieldIcon && abilities.shield) {
            const shieldOverlay = shieldIcon.querySelector('.cooldown-overlay');
            if (abilities.shield.active) {
                shieldIcon.classList.add('active');
                shieldIcon.classList.remove('cooldown');
                if (shieldOverlay) {
                    shieldOverlay.style.height = `${(1 - abilities.shield.duration / abilities.shield.maxDuration) * 100}%`;
                }
            } else if (abilities.shield.cooldown > 0) {
                shieldIcon.classList.remove('active');
                shieldIcon.classList.add('cooldown');
                if (shieldOverlay) {
                    shieldOverlay.style.height = `${(abilities.shield.cooldown / abilities.shield.maxCooldown) * 100}%`;
                }
            } else {
                shieldIcon.classList.remove('active', 'cooldown');
                if (shieldOverlay) {
                    shieldOverlay.style.height = '0%';
                }
            }
        }
        
        // 更新导弹图标
        const missileIcon = document.getElementById('missile-ability');
        if (missileIcon && abilities.missile) {
            const missileOverlay = missileIcon.querySelector('.cooldown-overlay');
            if (abilities.missile.cooldown > 0) {
                missileIcon.classList.add('cooldown');
                if (missileOverlay) {
                    missileOverlay.style.height = `${(abilities.missile.cooldown / abilities.missile.maxCooldown) * 100}%`;
                }
            } else {
                missileIcon.classList.remove('cooldown');
                if (missileOverlay) {
                    missileOverlay.style.height = '0%';
                }
            }
        }
        
        // 更新激光图标
        const laserIcon = document.getElementById('charge-ability');
        if (laserIcon && abilities.laser) {
            const laserOverlay = laserIcon.querySelector('.cooldown-overlay');
            if (abilities.laser.charging) {
                laserIcon.classList.add('active');
                laserIcon.classList.remove('cooldown');
                if (laserOverlay) {
                    laserOverlay.style.height = `${(1 - abilities.laser.chargeTime / 2) * 100}%`;
                }
            } else if (abilities.laser.cooldown > 0) {
                laserIcon.classList.remove('active');
                laserIcon.classList.add('cooldown');
                if (laserOverlay) {
                    laserOverlay.style.height = `${(abilities.laser.cooldown / abilities.laser.maxCooldown) * 100}%`;
                }
            } else {
                laserIcon.classList.remove('active', 'cooldown');
                if (laserOverlay) {
                    laserOverlay.style.height = '0%';
                }
            }
        }
        
    } catch (error) {
        console.error('更新技能图标时出错:', error);
    }
}

// 保存游戏设置
function saveSettings() {
    try {
        const volume = parseInt(document.getElementById('volume').value) || 50;
        const difficulty = document.getElementById('difficulty').value || 'medium';
        const enemySpeed = parseFloat(document.getElementById('enemy-speed').value) || 3;
        const screenMode = document.getElementById('screen-mode').value || 'windowed';
        
        // 更新游戏设置
        const gameSettings = {
            volume,
            difficulty,
            enemySpeed,
            screenMode,
            difficultySettings: {
                easy: {
                    enemySpawnRate: 0.005,
                    baseEnemySpeed: 1,
                    resourceSpawnRate: 0.01
                },
                medium: {
                    enemySpawnRate: 0.008,
                    baseEnemySpeed: 1.5,
                    resourceSpawnRate: 0.008
                },
                hard: {
                    enemySpawnRate: 0.012,
                    baseEnemySpeed: 2,
                    resourceSpawnRate: 0.005
                }
            }
        };

        // 更新显示
        document.getElementById('volume-value').textContent = volume;
        document.getElementById('enemy-speed-value').textContent = enemySpeed;

        // 应用设置
        if (gameState) {
            // 更新游戏参数
            const diffSettings = gameSettings.difficultySettings[difficulty];
            if (diffSettings) {
                gameState.enemySpawnRate = diffSettings.enemySpawnRate;
                gameState.baseEnemySpeed = diffSettings.baseEnemySpeed * enemySpeed;
                gameState.resourceSpawnRate = diffSettings.resourceSpawnRate;
            }
        }

        // 处理全屏模式
        if (screenMode === 'fullscreen') {
            document.documentElement.requestFullscreen();
        } else if (document.fullscreenElement) {
            document.exitFullscreen();
        }

        // 隐藏设置菜单
        document.getElementById('settings-menu').classList.add('hidden');
        
        // 如果在游戏中，显示暂停菜单
        if (gameState && gameState.paused) {
            document.getElementById('pause-menu').classList.remove('hidden');
        } else {
            // 否则返回主菜单
            document.getElementById('main-menu').classList.remove('hidden');
        }

    } catch (error) {
        console.error('保存设置时出错:', error);
    }
}

// 初始化星空背景
function initSpaceBackground() {
    const spaceBackground = document.getElementById('spaceBackground');
    if (!spaceBackground) return;

    // 清除现有的背景元素
    spaceBackground.innerHTML = '';

    // 创建星星
    for (let i = 0; i < 100; i++) {
        const star = document.createElement('div');
        star.className = 'star';
        star.style.left = `${Math.random() * 100}%`;
        star.style.top = `${Math.random() * 100}%`;
        star.style.width = `${Math.random() * 3}px`;
        star.style.height = star.style.width;
        star.style.setProperty('--duration', `${Math.random() * 3 + 2}s`);
        spaceBackground.appendChild(star);
    }

    // 创建流星
    for (let i = 0; i < 5; i++) {
        const shootingStar = document.createElement('div');
        shootingStar.className = 'shooting-star';
        shootingStar.style.left = `${Math.random() * 100}%`;
        shootingStar.style.top = `${Math.random() * 100}%`;
        shootingStar.style.setProperty('--duration', `${Math.random() * 2 + 1}s`);
        shootingStar.style.setProperty('--angle', `${Math.random() * 360}deg`);
        spaceBackground.appendChild(shootingStar);
    }

    // 创建星云
    for (let i = 0; i < 3; i++) {
        const nebula = document.createElement('div');
        nebula.className = 'nebula';
        nebula.style.left = `${Math.random() * 100}%`;
        nebula.style.top = `${Math.random() * 100}%`;
        
        // 随机选择星云颜色
        const colors = [
            ['0, 255, 136', '0, 184, 255'],  // 青绿色到蓝色
            ['255, 68, 68', '255, 136, 0'],  // 红色到橙色
            ['136, 0, 255', '255, 0, 255']   // 紫色到粉色
        ];
        const [color1, color2] = colors[Math.floor(Math.random() * colors.length)];
        
        nebula.style.setProperty('--color-1', color1);
        nebula.style.setProperty('--color-2', color2);
        spaceBackground.appendChild(nebula);
    }
}

// 退出游戏函数
function quitGame() {
    // 停止游戏循环
    if (gameState && gameState.animationFrameId) {
        cancelAnimationFrame(gameState.animationFrameId);
    }
    
    // 重置游戏状态
    gameState = null;
    gameContext = null;
    
    // 隐藏所有界面
    hideAllScreens();
    
    // 显示主菜单
    document.getElementById('main-menu').classList.remove('hidden');
}

// 绘制粒子效果
function drawParticles(ctx) {
    if (!ctx || !gameState || !gameState.particles) return;
    
    ctx.save();
    
    // 遍历所有粒子
    for (let i = gameState.particles.length - 1; i >= 0; i--) {
        const particle = gameState.particles[i];
        
        // 设置透明度
        ctx.globalAlpha = particle.life;
        
        // 设置颜色和发光效果
        ctx.fillStyle = particle.color;
        ctx.shadowColor = particle.color;
        ctx.shadowBlur = 10;
        
        // 绘制粒子
        ctx.beginPath();
        ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
        ctx.fill();
        
        // 更新粒子
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.life -= 0.02;
        
        // 如果粒子生命值耗尽，从数组中移除
        if (particle.life <= 0) {
            gameState.particles.splice(i, 1);
        }
    }
    
    ctx.restore();
}

// 更新玩家状态
function updatePlayer() {
    if (!gameState || !gameState.player) return;

    // 根据按键状态更新玩家位置
    let dx = 0;
    let dy = 0;

    if (keys.w) dy -= gameState.player.speed;
    if (keys.s) dy += gameState.player.speed;
    if (keys.a) dx -= gameState.player.speed;
    if (keys.d) dx += gameState.player.speed;

    // 对角线移动时进行速度标准化
    if (dx !== 0 && dy !== 0) {
        const normalizer = 1 / Math.sqrt(2);
        dx *= normalizer;
        dy *= normalizer;
    }

    // 更新玩家位置，确保不超出边界
    gameState.player.x = Math.max(20, Math.min(GAME_WIDTH - 20, gameState.player.x + dx));
    gameState.player.y = Math.max(20, Math.min(GAME_HEIGHT - 20, gameState.player.y + dy));

    // 更新玩家朝向（面向鼠标位置）
    if (gameState.mouse) {
        gameState.player.angle = Math.atan2(
            gameState.mouse.y - gameState.player.y,
            gameState.mouse.x - gameState.player.x
        );
    }

    // 如果按下空格键或鼠标，进行射击
    if (keys.space || gameState.mouse.down) {
        shoot();
    }

    // 恢复能量
    if (gameState.player.energy < gameState.player.maxEnergy) {
        gameState.player.energy = Math.min(
            gameState.player.maxEnergy,
            gameState.player.energy + 0.1
        );
    }
}

// 玩家射击函数
function shoot() {
    if (!gameState.player) return;
    
    const currentTime = Date.now();
    if (currentTime - gameState.player.lastShootTime < gameState.player.shootCooldown * 1000) return;
    
    const bullet = {
        x: gameState.player.x,
        y: gameState.player.y,
        angle: gameState.player.angle,
        speed: BULLET_CONFIG.speed,
        damage: 10 * (gameState.player.upgrades?.damage || 1),
        size: PLAYER_BULLET_SIZE,
        tracking: true,
        target: null,
        velocity: {
            x: Math.cos(gameState.player.angle) * BULLET_CONFIG.speed,
            y: Math.sin(gameState.player.angle) * BULLET_CONFIG.speed
        },
        creationTime: currentTime,
        lifeTime: 3000 // 子弹存活3秒
    };
    
    if (!gameState.bullets) {
        gameState.bullets = [];
    }
    
    gameState.bullets.push(bullet);
    gameState.player.lastShootTime = currentTime;
    
    createShootingEffect(bullet.x, bullet.y, bullet.angle);
}

// 更新游戏HUD（平视显示器）
function updateHUD(ctx) {
    if (!gameState.player) return;
    
    // 绘制血量条
    const healthBarWidth = 200;
    const healthBarHeight = 20;
    const healthBarX = 20;
    const healthBarY = 20;
    
    // 血量条背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(healthBarX, healthBarY, healthBarWidth, healthBarHeight);
    
    // 血量条
    const healthPercentage = gameState.player.health / gameState.player.maxHealth;
    ctx.fillStyle = `hsl(${healthPercentage * 120}, 70%, 50%)`;
    ctx.fillRect(healthBarX, healthBarY, healthBarWidth * healthPercentage, healthBarHeight);
    
    // 血量文字
    ctx.fillStyle = '#fff';
    ctx.font = '16px Arial';
    ctx.textAlign = 'center';
    ctx.fillText(
        `${Math.floor(gameState.player.health)}/${gameState.player.maxHealth}`,
        healthBarX + healthBarWidth / 2,
        healthBarY + healthBarHeight / 2 + 5
    );
    
    // 绘制击杀数（新位置）
    const killsX = GAME_WIDTH - 120;
    const killsY = 30;
    
    // 击杀数背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(killsX - 10, killsY - 20, 100, 40);
    
    // 击杀图标
    ctx.fillStyle = '#ff4444';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('💀', killsX, killsY);
    
    // 击杀数
    ctx.fillStyle = '#fff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText(`击杀: ${gameState.player.kills || 0}`, killsX + 30, killsY);
    
    // 绘制分数
    const scoreX = GAME_WIDTH - 120;
    const scoreY = 80;
    
    // 分数背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(scoreX - 10, scoreY - 20, 100, 40);
    
    // 分数图标
    ctx.fillStyle = '#00ff88';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('⭐', scoreX, scoreY);
    
    // 分数
    ctx.fillStyle = '#fff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText(`分数: ${gameState.player.score || 0}`, scoreX + 30, scoreY);
    
    // 绘制等级
    const levelX = GAME_WIDTH - 120;
    const levelY = 130;
    
    // 等级背景
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
    ctx.fillRect(levelX - 10, levelY - 20, 100, 40);
    
    // 等级图标
    ctx.fillStyle = '#00b8ff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('🔰', levelX, levelY);
    
    // 等级
    ctx.fillStyle = '#fff';
    ctx.font = '20px Arial';
    ctx.textAlign = 'left';
    ctx.fillText(`等级: ${gameState.player.level || 1}`, levelX + 30, levelY);
}

// 生成资源
function spawnResource() {
    if (!gameState) return;

    // 随机选择资源类型
    const types = ['health', 'energy', 'upgrade'];
    const type = types[Math.floor(Math.random() * types.length)];

    // 随机位置（确保不会太靠近边缘）
    const margin = 50;
    const x = margin + Math.random() * (GAME_WIDTH - 2 * margin);
    const y = margin + Math.random() * (GAME_HEIGHT - 2 * margin);

    // 创建资源对象
    const resource = {
        x: x,
        y: y,
        type: type,
        size: 10,
        value: type === 'upgrade' ? 1 : Math.floor(Math.random() * 20) + 10
    };

    // 初始化资源数组
    if (!gameState.resources) {
        gameState.resources = [];
    }

    // 添加资源
    gameState.resources.push(resource);
}

// 生成敌人
function spawnEnemy() {
    if (Math.random() > ENEMY_SPAWN_RATE) return;
    
    // 随机选择出生点（画面边缘）
    let x, y;
    if (Math.random() < 0.5) {
        // 在左右边缘
        x = Math.random() < 0.5 ? -50 : GAME_WIDTH + 50;
        y = Math.random() * GAME_HEIGHT;
    } else {
        // 在上下边缘
        x = Math.random() * GAME_WIDTH;
        y = Math.random() < 0.5 ? -50 : GAME_HEIGHT + 50;
    }
    
    const enemy = {
        x: x,
        y: y,
        health: 100,    // 将初始血量从 100 改为 50
        maxHealth: 100, // 将最大血量从 100 改为 50
        speed: BASE_ENEMY_SPEED * (1 + Math.random() * 0.5),
        size: 30,
        lastShootTime: 0,
        shootCooldown: 2,
        lastAttackTime: 0,
        damage: 10,
        projectiles: [],
        color: `hsl(${Math.random() * 360}, 70%, 50%)`
    };
    
    if (!gameState.enemies) {
        gameState.enemies = [];
    }
    if (!gameState.enemyBullets) {
        gameState.enemyBullets = [];
    }
    
    gameState.enemies.push(enemy);
}

// 更新资源
function updateResources() {
    if (!gameState || !gameState.resources || !gameState.player) return;

    for (let i = gameState.resources.length - 1; i >= 0; i--) {
        const resource = gameState.resources[i];
        
        // 计算与玩家的距离
        const dx = gameState.player.x - resource.x;
        const dy = gameState.player.y - resource.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 如果玩家靠近资源，收集它
        if (distance < 30) {
            // 根据资源类型应用效果
            switch (resource.type) {
                case 'health':
                    gameState.player.health = Math.min(
                        gameState.player.maxHealth,
                        gameState.player.health + resource.value
                    );
                    // 创建治疗特效
                    createHealEffect(resource.x, resource.y);
                    break;
                    
                case 'energy':
                    gameState.player.energy = Math.min(
                        gameState.player.maxEnergy,
                        gameState.player.energy + resource.value
                    );
                    // 创建能量特效
                    createEnergyEffect(resource.x, resource.y);
                    break;
                    
                case 'upgrade':
                    gameState.player.experience += resource.value * 10;
                    // 检查是否升级
                    checkLevelUp();
                    // 创建升级特效
                    createUpgradeEffect(resource.x, resource.y);
                    break;
            }
            
            // 添加分数
            gameState.player.score += resource.value * 5;
            
            // 移除已收集的资源
            gameState.resources.splice(i, 1);
        }
    }
}

// 创建治疗特效
function createHealEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    for (let i = 0; i < 8; i++) {
        const angle = (Math.PI * 2 / 8) * i;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * 2,
            vy: Math.sin(angle) * 2,
            life: 1,
            size: 3,
            color: '#ff4444'
        };
        gameState.particles.push(particle);
    }
}

// 创建能量特效
function createEnergyEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    for (let i = 0; i < 8; i++) {
        const angle = (Math.PI * 2 / 8) * i;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * 2,
            vy: Math.sin(angle) * 2,
            life: 1,
            size: 3,
            color: '#00b8ff'
        };
        gameState.particles.push(particle);
    }
}

// 创建升级特效
function createUpgradeEffect(x, y) {
    if (!gameState.particles) {
        gameState.particles = [];
    }
    
    for (let i = 0; i < 12; i++) {
        const angle = (Math.PI * 2 / 12) * i;
        const particle = {
            x: x,
            y: y,
            vx: Math.cos(angle) * 3,
            vy: Math.sin(angle) * 3,
            life: 1,
            size: 4,
            color: '#00ff88'
        };
        gameState.particles.push(particle);
    }
}

// 检查升级
function checkLevelUp() {
    if (!gameState || !gameState.player) return;
    
    const expNeeded = gameState.player.level * 100;
    
    if (gameState.player.experience >= expNeeded) {
        // 升级
        gameState.player.level++;
        gameState.player.experience -= expNeeded;
        
        // 恢复生命值和能量
        gameState.player.health = gameState.player.maxHealth;
        gameState.player.energy = gameState.player.maxEnergy;
        
        // 显示升级消息
        showMessage(`升级！当前等级: ${gameState.player.level}`);
    }
}

// 更新敌人
function updateEnemies() {
    if (!gameState || !gameState.enemies || !gameState.player) return;

    for (let i = gameState.enemies.length - 1; i >= 0; i--) {
        const enemy = gameState.enemies[i];
        
        // 计算到玩家的方向
        const dx = gameState.player.x - enemy.x;
        const dy = gameState.player.y - enemy.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 更新敌人角度（面向玩家）
        enemy.angle = Math.atan2(dy, dx);
        
        // 移动敌人
        if (distance > ENEMY_ATTACK_RANGE) {
            enemy.x += Math.cos(enemy.angle) * enemy.speed;
            enemy.y += Math.sin(enemy.angle) * enemy.speed;
        }
        
        // 检查攻击冷却
        const currentTime = Date.now();
        if (distance <= ENEMY_ATTACK_RANGE && 
            currentTime - enemy.lastAttackTime >= ENEMY_ATTACK_COOLDOWN) {
            
            // 发射子弹
            const projectile = {
                x: enemy.x,
                y: enemy.y,
                angle: enemy.angle,
                speed: ENEMY_PROJECTILE_SPEED,
                damage: enemy.damage || 10,
                size: ENEMY_BULLET_SIZE,
                velocity: {
                    x: Math.cos(enemy.angle) * ENEMY_PROJECTILE_SPEED,
                    y: Math.sin(enemy.angle) * ENEMY_PROJECTILE_SPEED
                },
                creationTime: currentTime,
                lifeTime: 3000 // 敌人子弹存活3秒
            };
            
            if (!gameState.enemyBullets) {
                gameState.enemyBullets = [];
            }
            
            gameState.enemyBullets.push(projectile);
            enemy.lastAttackTime = currentTime;
            
            // 创建射击特效
            createEnemyShootingEffect(enemy.x, enemy.y, enemy.angle);
        }
        
        // 更新敌人子弹
        updateEnemyProjectiles(enemy);
        
        // 检查敌人是否超出屏幕太远（清理超出范围的敌人）
        const margin = 100;
        if (enemy.x < -margin || enemy.x > GAME_WIDTH + margin ||
            enemy.y < -margin || enemy.y > GAME_HEIGHT + margin) {
            gameState.enemies.splice(i, 1);
            continue;
        }
    }
}

// 更新敌人子弹
function updateEnemyProjectiles(enemy) {
    if (!enemy.projectiles) return;

    for (let i = enemy.projectiles.length - 1; i >= 0; i--) {
        const projectile = enemy.projectiles[i];
        
        // 更新子弹位置
        projectile.x += Math.cos(projectile.angle) * projectile.speed;
        projectile.y += Math.sin(projectile.angle) * projectile.speed;
        
        // 更新子弹拖尾效果
        if (!projectile.trail) {
            projectile.trail = [];
        }
        projectile.trail.unshift({ x: projectile.x, y: projectile.y });
        if (projectile.trail.length > 5) {
            projectile.trail.pop();
        }
        
        // 检查是否击中玩家
        if (!gameState.player.abilities.shield.active) {
            const dx = projectile.x - gameState.player.x;
            const dy = projectile.y - gameState.player.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance < 20) {
                // 造成伤害
                gameState.player.health -= projectile.damage;
                
                // 创建击中效果
                createHitEffect(projectile.x, projectile.y, '#ff4444');
                
                // 移除子弹
                enemy.projectiles.splice(i, 1);
                
                // 检查游戏结束
                if (gameState.player.health <= 0) {
                    gameOver();
                }
                
                continue;
            }
        }
        
        // 移除超出屏幕的子弹
        if (projectile.x < 0 || projectile.x > GAME_WIDTH ||
            projectile.y < 0 || projectile.y > GAME_HEIGHT) {
            enemy.projectiles.splice(i, 1);
        }
    }
}

// 添加经验值
function addExperience(amount) {
    if (!gameState || !gameState.player) return;
    
    gameState.player.experience += amount;
    
    // 检查是否可以升级
    const expNeeded = gameState.player.level * 100;
    if (gameState.player.experience >= expNeeded) {
        // 升级
        gameState.player.level++;
        gameState.player.experience -= expNeeded;
        
        // 提升属性
        gameState.player.maxHealth += 20;
        gameState.player.maxEnergy += 10;
        
        // 恢复生命值和能量
        gameState.player.health = gameState.player.maxHealth;
        gameState.player.energy = gameState.player.maxEnergy;
        
        // 显示升级消息
        showMessage(`升级！等级 ${gameState.player.level}`);
        
        // 创建升级特效
        createLevelUpEffect();
    }
}

// 创建升级特效
function createLevelUpEffect() {
    if (!gameState || !gameState.player) return;
    
    // 创建环形粒子
    for (let i = 0; i < 24; i++) {
        const angle = (Math.PI * 2 / 24) * i;
        const particle = {
            x: gameState.player.x,
            y: gameState.player.y,
            vx: Math.cos(angle) * 4,
            vy: Math.sin(angle) * 4,
            life: 1,
            size: 5,
            color: '#00ff88'
        };
        
        if (!gameState.particles) {
            gameState.particles = [];
        }
        gameState.particles.push(particle);
    }
}

// 绘制导弹
function drawMissiles(ctx) {
    if (!ctx || !gameState || !gameState.missiles) return;
    
    gameState.missiles.forEach(missile => {
        ctx.save();
        
        // 绘制导弹主体
        ctx.translate(missile.x, missile.y);
        ctx.rotate(missile.angle);
        
        // 导弹身体
        ctx.fillStyle = '#ff4400';
        ctx.beginPath();
        ctx.moveTo(15, 0);
        ctx.lineTo(-10, 8);
        ctx.lineTo(-10, -8);
        ctx.closePath();
        ctx.fill();
        
        // 添加发光效果
        ctx.shadowColor = '#ff8800';
        ctx.shadowBlur = 10;
        ctx.strokeStyle = '#ff8800';
        ctx.lineWidth = 2;
        ctx.stroke();
        
        // 绘制尾焰
        const gradient = ctx.createLinearGradient(-15, 0, -30, 0);
        gradient.addColorStop(0, 'rgba(255, 68, 0, 0.8)');
        gradient.addColorStop(1, 'rgba(255, 68, 0, 0)');
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.moveTo(-10, 6);
        ctx.lineTo(-30, 0);
        ctx.lineTo(-10, -6);
        ctx.closePath();
        ctx.fill();
        
        // 绘制导弹拖尾
        if (!missile.trail) {
            missile.trail = [];
        }
        
        ctx.restore();
        
        // 绘制拖尾效果
        if (missile.trail.length > 0) {
            ctx.beginPath();
            ctx.moveTo(missile.trail[0].x, missile.trail[0].y);
            
            for (let i = 1; i < missile.trail.length; i++) {
                const point = missile.trail[i];
                ctx.lineTo(point.x, point.y);
            }
            
            ctx.strokeStyle = 'rgba(255, 68, 0, 0.3)';
            ctx.lineWidth = 4;
            ctx.stroke();
        }
        
        // 更新拖尾位置
        missile.trail.unshift({ x: missile.x, y: missile.y });
        if (missile.trail.length > 10) {
            missile.trail.pop();
        }
    });
}

// 添加分数
function addScore(amount) {
    if (!gameState || !gameState.player) return;
    
    // 增加分数
    gameState.player.score += amount;
    
    // 创建分数特效
    createScoreEffect(amount);
    
    // 检查是否达到高分
    checkHighScore();
}

// 创建分数特效
function createScoreEffect(amount) {
    if (!gameState || !gameState.player) return;
    
    // 创建浮动文字效果
    const scoreText = {
        x: gameState.player.x,
        y: gameState.player.y - 30,
        text: `+${amount}`,
        life: 1,
        vy: -1,
        alpha: 1
    };
    
    if (!gameState.scoreTexts) {
        gameState.scoreTexts = [];
    }
    
    gameState.scoreTexts.push(scoreText);
}

// 检查高分
function checkHighScore() {
    if (!gameState || !gameState.player) return;
    
    // 获取当前最高分
    const highScore = localStorage.getItem('highScore') || 0;
    
    // 如果当前分数超过最高分
    if (gameState.player.score > highScore) {
        // 更新最高分
        localStorage.setItem('highScore', gameState.player.score);
        
        // 显示新纪录消息
        showMessage('新纪录！');
        
        // 创建特殊的视觉效果
        createHighScoreEffect();
    }
}

// 创建高分特效
function createHighScoreEffect() {
    if (!gameState || !gameState.player) return;
    
    // 创建螺旋粒子效果
    for (let i = 0; i < 36; i++) {
        const angle = (Math.PI * 2 / 36) * i;
        const radius = 30;
        
        const particle = {
            x: gameState.player.x + Math.cos(angle) * radius,
            y: gameState.player.y + Math.sin(angle) * radius,
            vx: Math.cos(angle) * 3,
            vy: Math.sin(angle) * 3,
            life: 1,
            size: 4,
            color: '#ffff00'
        };
        
        if (!gameState.particles) {
            gameState.particles = [];
        }
        
        gameState.particles.push(particle);
    }
}

// 更新分数文字效果
function updateScoreTexts(ctx) {
    if (!ctx || !gameState || !gameState.scoreTexts) return;
    
    for (let i = gameState.scoreTexts.length - 1; i >= 0; i--) {
        const scoreText = gameState.scoreTexts[i];
        
        // 更新位置和生命值
        scoreText.y += scoreText.vy;
        scoreText.life -= 0.02;
        scoreText.alpha = scoreText.life;
        
        // 绘制文字
        ctx.save();
        ctx.fillStyle = `rgba(255, 255, 255, ${scoreText.alpha})`;
        ctx.font = '20px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(scoreText.text, scoreText.x, scoreText.y);
        ctx.restore();
        
        // 移除已消失的文字
        if (scoreText.life <= 0) {
            gameState.scoreTexts.splice(i, 1);
        }
    }
}